package handler

import (
	"filestore-rebuild/db"
	"filestore-rebuild/models"
	"filestore-rebuild/util"
	"filestore-rebuild/util/jwtUtil"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	password_sal = "#90283217C"
)

// UserSignupHandler 用户注册接口
func UserSignupHandler(c *gin.Context) {
	username := c.Request.FormValue("username")
	password := c.Request.FormValue("password")
	if len(username) < 3 || len(password) < 3 {
		c.JSON(http.StatusOK, util.Resp{Code: -1, Msg: "username or password to short"})
		return
	}
	usernameExists := db.CheckUsernameExistsORM(username)
	if usernameExists {
		c.JSON(http.StatusOK, util.Resp{Code: -1, Msg: "username already exists!"})
		return
	}
	encPasswd := util.MD5([]byte(password + password_sal))
	signupSuc := db.InsertUser(username, encPasswd)
	if !signupSuc {
		c.JSON(http.StatusOK, util.Resp{Code: 1, Msg: "Signup failed"})
		return
	}
	c.JSON(http.StatusOK, util.Resp{Code: 1, Msg: "Signup success"})

}

// UserLoginHandler 用户登录接口
func UserLoginHandler(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")
	encPassword := util.MD5([]byte(password + password_sal))
	_, err := db.SelectUserByUserNameAndPasswd(username, encPassword)
	if err != nil {
		c.AsciiJSON(http.StatusOK, util.Resp{
			Code: -1,
			Msg:  "username or password wrong",
			Data: nil,
		})
		return
	}
	token, err := jwtUtil.GenerateToken(username)
	if err != nil {
		c.AsciiJSON(http.StatusOK, util.Resp{
			Code: -2,
			Msg:  "server error",
			Data: nil,
		})
	}
	c.JSON(http.StatusOK, util.Resp{
		Code: 1,
		Msg:  "Login success",
		Data: token,
	})
}

// UserInfoHandler 用户信息接口
func UserInfoHandler(c *gin.Context) {
	username := c.Request.Context().Value("username").(string)

	userInfo, err := db.SelectUserByUserName(username)
	if err != nil {
		c.AsciiJSON(http.StatusOK, util.Resp{
			Code: -3,
			Msg:  "Get user info failed",
		})
		return
	}
	c.AsciiJSON(http.StatusOK, util.Resp{
		Code: 1,
		Msg:  "OK",
		Data: userInfo,
	})
}

// UpdateUserInfoHandler 更新用户信息接口
func UpdateUserInfoHandler(c *gin.Context) {
	username := c.Request.Context().Value("username").(string)
	email := c.Request.FormValue("email")
	phone := c.Request.FormValue("phone")
	user := models.User{UserName: username, Email: email, Phone: phone}
	updateUserSuc := db.UpdateUser(user)
	if !updateUserSuc {
		c.JSON(http.StatusOK, util.Resp{Code: -1, Msg: "update failed"})
		return
	}
	c.JSON(http.StatusOK, util.Resp{Code: 1, Msg: "update success"})

}
